<?php
/**
 * [KeCms] Copyright (c) 2017 kecms.cn
 * [Author] King east ( 1207877378@qq.com )
 */

namespace app\admin\controller\wx;


use app\common\model\WxTemplate;
use ke\Controller;
use think\Validate;
use wx\Message;

class TemplateController extends Controller
{
    public function lists()
    {
        if($this->isAjax()){
            $page=input('get.page',1,'intval');
            $size=input('get.size',20,'intval');
            $start=($page-1)*$size;

            $where=null;

            $list=WxTemplate::where($where)->limit($start,$size)->select();
            $total=WxTemplate::where($where)->count();

            $this->result(['list'=>$list,'total'=>$total]);
        }
        return $this->fetch();
    }

    /**
     * 编辑
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        $form=getForm();
        if(empty($form['type'])){
            $this->error('参数错误');
        }
        $data=WxTemplate::where('type',$form['type'])->find();
        if(!$data){
            $this->error('模板不存在或已经删除');
        }
        $data->id=$form['id'];
        $data->save();
        $this->success('保存成功');
    }


    public function send()
    {
        $type=input('get.type');
        if(empty($type)){
            $this->error('参数错误');
        }
        $data=WxTemplate::where('type',$type)->find();
        if(!$data){
            $this->error('模板不存在或已经删除');
        }
        if($this->isPost()){
            $form=getForm();
            $vali=new Validate([
                'touser|接收者'=>'require|max:50'
            ]);
            if(!$vali->check($form)){
                $this->error($vali->getError());
            }
            list($bool,$msg)=Message::sendTemplate($form['touser'],$data->id,'',[
                'first'=>[
                    'value'=>'恭喜你购买成功',
                    'color'=>'#173177'
                ],
                'keyword1'=>[
                    'value'=>'巧克力',
                    'color'=>'#173177'
                ],
                'keyword2'=>[
                    'value'=>get_order_id(),
                    'color'=>'#173177'
                ],
                'keyword3'=>[
                    'value'=>'39.8元',
                    'color'=>'#173177'
                ],
                'keyword4'=>[
                    'value'=>date('Y年m月d日'),
                    'color'=>'#173177'
                ],
                'remark'=>[
                    'value'=>'欢迎再次购买！',
                    'color'=>'#173177'
                ],
            ]);
            if($bool){
                $this->success('发送成功');
            }else{
                $this->error($msg);
            }

        }
        $this->assign('data',[
            'item'=>$data
        ]);
        return $this->fetch();
    }

}